package com.vip.jwt.common.utils.cnmobile;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.vip.jwt.common.utils.sign.CNMobileSignUtil;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * 中国移动能力开放商店语音通知工具类
 */
public class CNMobileCallUtil {

    @Getter
    private static String API_KEY;

    @Getter
    private static String SECRET_KEY;

    @Value("${cn-mobile-apikey}")
    public void setApiKey(String apiKey) {
        API_KEY = apiKey;
    }

    @Value("${cn-mobile-secretkey}")
    public void setSecretKey(String secretKey) {
        SECRET_KEY = secretKey;
    }

    /**
     * 语音通知
     * @param voiceNumber 主叫号码
     * @param phone 被叫号码
     * @param templateId 模板ID
     * @param templateParams 模板参数
     * @return
     */
    public static String call(String voiceNumber,String phone,Integer templateId,Map<String,String> templateParams){
        String url = "http://dev.cmccopen.cn/api/v1/voice/voiceNotify";
        Map<String,Object> params = new HashMap<>(16);
        params.put("voiceNumber",voiceNumber);
        params.put("to",phone);
        //重复次数
        params.put("playTimes",2);
        params.put("templateId",templateId);
        params.put("templateParameter", templateParams);
        //非必填
        //params.put("respUrl","http://127.0.0.1/");
        long time = System.currentTimeMillis();
        String signStr = null;
        try {
            signStr = CNMobileSignUtil.MD5(API_KEY + SECRET_KEY + time);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("apiKey",API_KEY);
        jsonObject.put("time",time);
        jsonObject.put("sign",signStr);
        String jsonStr = JSONUtil.toJsonStr(jsonObject);
        String authorizationBase64 = Base64.encode(jsonStr,"UTF-8");
        String paramsStr = JSONUtil.toJsonStr(params);
        return HttpRequest.post(url)
                .header("Content-Type","application/json;charset=UTF-8")
                .header("Authorization",authorizationBase64)
                .body(paramsStr)
                .execute().body();
    }

}
